//
//  ViewController.m
//  CustomKVO
//
//  Created by 岚海网络 on 2018/11/23.
//  Copyright © 2018年 岚海网络. All rights reserved.
//

#import "ViewController.h"
#import "LJMPerson.h"

@interface ViewController ()

/**
 * param:strong
 
 KVO监听这里必须使用strong的强引用，否则当viewcontroller释放了，person在注册时就拿不到self；
 但是
 KVO的仍然会走代理方法observeValueForKeyPath
 给释放了地址再发消息------------------------crash---------------------
 
 * return:<#返回值#>
 */
@property (nonatomic , strong) LJMPerson * person ;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    _person = [[LJMPerson alloc] init];
    
    
    #pragma mark - person 不会强引用self
    /* 注册 */
    [_person addObserver:self forKeyPath:NSStringFromSelector(@selector(name)) options:(NSKeyValueObservingOptionNew) context:nil];
    
}

/* 监听方法 */
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    NSLog(@"%@",change);
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    static int a;
    
    #pragma mark - 手动模式的触发方法
    /* KVO的值即将改变 */
    [_person willChangeValueForKey:@"name"];
    
//    _person.name = [NSString stringWithFormat:@"%d",a ++];
    
    /* KVO的值已经改变 */
    [_person didChangeValueForKey:@"name"];
    
    
    /**
     * param:KVO的触发与是否调用setter方法没有关系
     
     只要执行了willChangeValueForKey或didChangeValueForKey
     KVO就会被触发
     * return:<#返回值#>
     */
    
}

- (void)dealloc
{
    [self removeObserver:self forKeyPath:NSStringFromSelector(@selector(name))];
}


@end
